import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution1().subsetsWithDup(new int[]{1,2,2}));
    }
}

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        backtracking(nums, 0, new ArrayDeque<>(), ans);
        return ans;
    }

    void backtracking(int[] nums, int i, Deque<Integer> cur, List<List<Integer>> ans) {
        if (i == nums.length) {
            ans.add(new ArrayList<>(cur));
            return;
        }

        cur.offerLast(nums[i]);
        backtracking(nums, i + 1, cur, ans);
        cur.pollLast();

        i++;
        while (i < nums.length && nums[i] == nums[i - 1]) {
            i++;
        }
        backtracking(nums, i, cur, ans);
    }
}

//二值mask迭代
class Solution1 {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int mask = 0; mask < 1 << nums.length; mask++) {
            Deque<Integer> subset = new ArrayDeque<>();
            boolean flag = true;
            for (int i = 0; i < nums.length; i++) {
                if ((mask >> i & 1) == 1) {
                    if (i > 0 && nums[i] == nums[i - 1] &&(mask >> (i - 1) & 1) == 0) {
                        flag = false;
                        break;
                    }
                    subset.offerLast(nums[i]);
                }
            }
            if (flag) {
                ans.add(new ArrayList<>(subset));
            }
        }
        return ans;
    }
}